<template>
	<view class="container" v-if="loaded">
		<form>
			<view class="cu-form-group">
				<view class="title ">注册手机号</view>
				<input class="left" name="input" v-model="userInfo.mobile" disabled></input>
			</view>
			<view class="cu-form-group">
				<view class="title flex">姓名<view class="require">*</view>
				</view>
				<input placeholder="请填写姓名" name="input" class="left" v-model="userInfo.name"></input>
			</view>
			<view class="cu-form-group">
				<view class="title flex">性别<view class="require">*</view>
				</view>
				<picker  @change="PickerChange" :value="index" :range="picker">
					<view class="picker">
						{{userInfo.sex!=undefined&&userInfo.sex!=''?(userInfo.sex=='boy'?'男':'女'):'请选择'}}
					</view>
				</picker>
			</view>
			<view class="cu-form-group">
				<view class="title flex">出生年份({{year-userInfo.birthday}}岁)<view class="require">*</view>
				</view>
				<picker mode="date" :value="date" start="1950" :end="year-18" fields="year" @change="DateChange">
					<view class="picker">
						{{userInfo.birthday!=undefined&&userInfo.birthday!=''?userInfo.birthday:'请选择'}}
					</view>
				</picker>
			</view>

      <view class="cu-form-group">
        <view class="title flex">最高学历
        </view>
        <picker  @change="eduChange" :value="eduIndex" :range="edus">
          <view class="picker">
            {{userInfo.education!=undefined&&userInfo.education!=''?userInfo.education:'请选择'}}
          </view>
        </picker>
      </view>
      <view class="cu-form-group">
        <view class="title flex">专业</view>
        <input v-model="userInfo.major" placeholder="请填写专业" name="input" class="left"></input>
      </view>
      <view class="cu-form-group">
        <view class="title flex">毕业年份
        </view>
        <picker mode="date" :value="userInfo.year" :start="year-19" :end="year+1" fields="year" @change="yearChange">
          <view class="picker">
            {{userInfo.year!=undefined&&userInfo.year!=''?userInfo.year:'请选择'}}
          </view>
        </picker>
      </view>

<!--			<view class="cu-form-group">-->
<!--				<view class="title flex">民族</view>-->
<!--				<picker  @change="nationChange" :value="nationIndex" :range="nations">-->
<!--					<view class="picker">-->
<!--						{{userInfo.nation!=undefined&&userInfo.nation!=''?userInfo.nation:'请选择'}}-->
<!--					</view>-->
<!--				</picker>-->
<!--			</view>-->
			<!-- <view class="cu-form-group">
				<view class="title flex">常住地</view>
				<input placeholder="请填写常住地址" name="input" class="left"></input>
			</view> -->
			<view class="cu-form-group">
				<view class="title flex">期望就业地</view>
				<uni-citys :defaultValue="userInfo.address_name" placeholder="请选择" @change='change'></uni-citys>
			</view>
<!--			<view class="cu-form-group">-->
<!--				<view class="title flex">毕业院校</view>-->
<!--				<input v-model="userInfo.college" placeholder="请填写毕业院校" name="input" class="left"></input>-->
<!--			</view>-->
			<view class="cu-form-group">
				<!-- <view class="title flex">我的就业类别</view>
				<input v-model="userInfo.position" placeholder="请填写期望岗位" name="input" class="left"></input> -->
        <view class="title flex">期望岗位类别
        </view>
<!--        <uni-combox v-if="typeData.length>0"  placeholder="请选择岗位类别" :candidates="typeData"-->
<!--        ></uni-combox>-->
        <view @click="openFruit" class="flex">
          <view class="placeholder" v-if="resultFruit==undefined||resultFruit==''">请选择岗位类别</view>
          <view class="as-content" v-else>{{resultFruit}}</view>
          <uni-icons type="forward" size="16" color="#c0c4cc" class="customer-icon"></uni-icons>
        </view>
<!--        <combox-search v-if="typeData.length>0" labelWidth="100px" emptyTips="无匹配选项" :unikey="3" :isCheckBox="true"-->
<!--                       :isJSON="true" :keyName="keyName" :keyId="keyId" :candidates="typeData" placeholder="请选择所在城市"-->
<!--                       @getValue="getValue($event,'json')" :initValue="initValue"></combox-search>-->
<!--				<picker  @change="typeChange" :value="typeIndex" :range="type" mu>-->
<!--					<view class="picker">-->
<!--						{{userInfo.type!=undefined&&userInfo.type!=''?typeState.type[userInfo.type]:'请选择'}}-->
<!--					</view>-->
<!--				</picker>-->
			</view>
      <view class="cu-form-group">
        <view class="title flex">与本人关系</view>
        <picker :value="userInfo.relation" :range="relations" @change="relaChange">
          <view class="picker">
            {{userInfo.relation!=undefined?relations[(userInfo.relation)]:'请选择'}}
          </view>
        </picker>
      </view>
			<view class="cu-bar bg-white" style="border-top: 1rpx solid #eee;">
				<view class="action">
					上传简历附件
				</view>
				<view class="action" @click="goPreview(pdfData)">
          查看简历模板<span class="cuIcon-right"></span>
				</view>
			</view>
			<view class="cu-form-group">
          <view class="grid col-4 grid-square flex-sub " style="margin-bottom:50px">
            <view class="bg-img" v-for="(item,index) in imgList" :key="index"
                  :data-url="imgList[index]">
              <image src="../../../static/images/jianli.png" mode="aspectFill" @tap="showImgs(imgList,index)"></image>
              <view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index">
                <text class='cuIcon-close'></text>
              </view>
            </view>
            <view class="solids"  v-if="imgList.length<1">
              <text class='cuIcon-cameraadd' @tap="ChooseImage"></text>
            </view>
          </view>
      </view>
			<view class="">

				<button class="cu-btn block bg-blue margin-tb-sm lg" @tap="save()" v-if="saving==false">
					保存</button>
				<button class="cu-btn block bg-blue margin-tb-sm lg" v-else>
					<text class="cuIcon-loading2 cuIconfont-spin"></text> 保存中</button>
			</view>
		</form>
    <niceui-popup-select ref="showFruit" :columns="typeData" :selectValue="fruitId" :is-search="false"
                         :option="{label:'name', value:'id'}" @confirm="confirmFruit"></niceui-popup-select>
	</view>
</template>

<script>
	import uniCitys from '@/components/biaofun-region/biaofun-region.vue';
  import UniIcons from "@/components/uni-icons_bak/uni-icons";
  import NiceuiPopupSelect from "../../../components/niceui-popup-select/niceui-popup-select";

	// import {
	//     mapMutations
	// } from 'vuex';
	export default {
		components: {
      NiceuiPopupSelect,
      UniIcons,
			uniCitys,
		},
		data() {
			return {
				saving:false,
				userInfo: {
          relation:0,
          birthday:this.year-18,
          year:this.year,
          position:[],
        },
				index: -1,
        loaded:false,
        keyName: 'name',
        keyId: "id",
        initValue: [],
        selectBgColor: '#FCF681',
        selectColor: 'red',
        cateIndex:'',
				year: new Date().getFullYear(),
				typeIndex: -1,
				eduIndex: -1,
				nationIndex: -1,
				picker: ['男', '女'],
				nations: [],
				edus: ['初中', '高中', '大专', '本科', '硕士', '博士'],
        relations: ['本人', '子女', '亲属', '好友', '同学'],
				type: [],
				typeState: [],
				typeArr:[],
				date: '2002',
				area_id: '',
				imgList: [],
        pdfData: [],
        typeData: [],
        fruitId:[],
        fruitName:[],
				uId: 0,
			};
		},
    computed:{
      resultFruit(){
        this.fruitName = this.fruitName.join(",")
        return this.fruitName;
      },
    },
		onLoad(options) {
			/**
			 * 修复app端点击除全部订单外的按钮进入时不加载数据的问题
			 * 替换onLoad下代码即可
			 */
			// this.tabCurrentIndex = +options.state;
			// // #ifndef MP
			// this.loadData()
			// // #endif
			// // #ifdef MP
			// if(options.state == 0){
			// 	this.loadData()
			// }
			// // #endif
			this.uId = uni.getStorageSync('userId');
			let obj = uni.getSystemInfoSync();
			let clientHeight = obj.screenHeight;
			this.scrollHeight = clientHeight - 150 + 'px';
			console.log(this.scrollHeight);
			this.userInfo = uni.getStorageSync('userInfo');
			this.getTableState();
			// this.getNations();
			this.getCates();
			this.getSys();
			this.getUserInfo();
		},
		methods: {
      //预览pdf
      goPreview(item) {

        let t = this
        if(item==undefined||item==''){
          uni.showToast({
            title:'敬情期待...',
            icon:'none'
          })
          return
        }
        // let url = this.$IMG_URL+'files/'+path
        let url = item.value
        console.info("🚀 ~ file:tabbar-1 method:goPreview line:305 -----", url)
        // if(path=='') return
        uni.showLoading({
          title: '下载文档中...',
          mask: true
        });
        // if(path=='') return
        uni.downloadFile({
          // 示例 url，并非真实存在
          // url: 'http://zzb.aottov.com/uploads/test.pdf',
          url: url,
          success: function (res) {
            console.log(res)
            const filePath = res.tempFilePath
            uni.openDocument({
              filePath: filePath,
              showMenu: true, // 是否显示右上角菜单
              // fileType: 'pdf',
              success: function (res) {
                console.log('打开文档成功')
                // uni.showToast({
                //   title: '打开文档成功！',
                //   icon: 'none'
                // });
              }
              ,fail(e){
                console.log(e)
                uni.showToast({
                  title: '打开文档失败！',
                  icon: 'none'
                });
              }
            })
          },fail(e){
            console.log(e)
            uni.showToast({
              title: '文档下载失败！',
              icon: 'none'
            });
          }
        })
      },
      //获取后端配置
      async getSys(){
        let t = this;
        let param = {
          'setting':'platform',
        };

        let data = await this.$http.post(
          'wx/platConfigs', //可以直接放链接(将不启用全局定义域名)
          param,
        );
        t.pdfData = data[3];
        console.log(t.pdfData);
      },
      openFruit(){
        this.$refs.showFruit.showPopup()
      },
      confirmFruit(value,data) {
        this.fruitId = value
        this.fruitName = data.map(it=>it.name)
        this.$refs.showFruit.closePopup()
      },
      //获取后端岗位类型
      async getCates(){
        let param = '';
        let t = this;
        let data = await this.$http.get(
          'wx/get_all', //可以直接放链接(将不启用全局定义域名)
          param,
        );
        t.typeData = data
        console.log(t.typeData);
        // this.defaultValue ? this.setDefaultValue() : '';

      },

			async getTableState(){
				let param = 'jobs';
				let t = this;
				let data = await this.$http.get(
					'wx/common_get_table_status/'+param, //可以直接放链接(将不启用全局定义域名)
				);
				// t.provinceData=[''];
				// t.citysData = ['请选择']var arr = []
				t.typeState = data
				uni.setStorageSync('jobState',data);
				let obj = data.type
				t.type=[]
				t.typeArr=[]
				for (let i in obj) {
					t.type.push(obj[i]);
					t.typeArr.push(i);
				}
				// console.log(arr);
				// t.PositionCategory = data.type
				console.log(data);
			},
			async getNations(){

				let t = this;
				let data = await this.$http.get(
					'wx/nation_list', //可以直接放链接(将不启用全局定义域名)
				);
				// t.provinceData=[''];
				// t.citysData = ['请选择']var arr = []
				// t.nations = data

				let obj = data
				for (let i in obj) {
					t.nations.push(obj[i].name);
				}
				// console.log(t.nations);
				// t.PositionCategory = data.type
				// console.log(data);
			},
			async save(){
				let t = this;
				// t.saving = true
				console.log(t.imgList)
				console.log(t.userInfo);
				if(!t.userInfo.name){
					uni.showToast({
            title:'请填写姓名',
            icon:'none'
          })
          return
				}

        if(!t.fruitId.length){
          uni.showToast({
            title:'请选择期望岗位类型',
            icon:'none'
          })
          return
        }
        t.userInfo.position = t.fruitId;
        t.userInfo.position_name = t.fruitName
				// if(t.imgList.length>0){
				// 	t.userInfo.path = t.imgList[0].path
				// }
				// return;
				let param = t.userInfo;
				this.$http.request({
					url: 'wx/job_seekers/'+t.uId,
					method: "POST", // POST、GET、PUT、DELETE、JSONP，具体说明查看官方文档
					data: param,
					header: { //默认 无 说明：请求头
						'Content-Type': 'application/json'
					},
					isFactory: true,
				}).then(function (res) {
					t.saving = false
					let data = res
					console.log(data);

					uni.showToast({
						title:'保存成功',
						icon:'none',
					})
					// t.getUserInfo();
					// uni.setStorageSync('userInfo',data);
					setTimeout(() => {
						// this.$api.msg(`保存成功`);
						uni.navigateBack({})
					}, 1500);
					return
					//这里只会在接口是成功状态返回
				}).catch(function (e) {
					t.saving = false
					//这里只会在接口是失败状态返回，不需要去处理错误提示
					console.log(e);
					uni.showToast({
						title:'保存失败',
						icon:'none',
					})
					// this.$api.error(`保存失败`);
				});
				// t.saving = false


			},
      //查看图片
      showImgs(urls,index){
        if(urls!=undefined){
          uni.previewImage({
            current: urls[index], // 当前显示图片的http链接
            urls: urls // 需要预览的图片http链接列表
          })
        }
      },
			ChooseImage() {
        let t = this
        console.info("🚀 ~ file:userInfo method:ChooseImage line:431 -----")
        uni.chooseImage({
          count: 1, //默认9
          sizeType: ["compressed"],
          sourceType: ['album', 'camera'],
          success: (res) => {
            console.log(res)
            this.imgList = res.tempFiles;
            // return
            if (this.imgList.length > 0) {
              let path = this.imgList[0].path
              uni.uploadFile({
                url: this.$http.fileUrl, //仅为示例，非真实的接口地址
                filePath: path,
                name: 'file',
                success: (ret) => {
                  console.log(ret.data);
                  var data = JSON.parse(ret.data)
                  var path = data.data.url
                  t.userInfo.path = path
                  console.log(path);
                  // t.confirm()
                }
              });
              // this.$http.fileUrl({
              //   filePath: [{path:path}], // 必填 临时文件路径 格式: [{path: "图片地址"}]
              //   name: 'file',
              // }).then(res => {
              // 	console.log("全部上传完返回结果：",res);
              // });
            } else {
              // uni.showToast({
              //   title:'请选择正确的文档',
              //   icon:'none'
              // })
              // this.$api.msg(`请选择正确的文档`);

            }
          },fail(res) {
            console.info("🚀 ~ file:userInfo method:fail line:470 -----", res)
          }
        });

			},
			ViewImage(e) {
				uni.previewImage({
					urls: this.imgList,
					current: e.currentTarget.dataset.url
				});
			},
      ViewPdf(e) {
        console.info("🚀 ~ file:userInfo method:ViewPdf line:439 -----",e )
        wx.openDocument({
          filePath: e.path,
          showMenu:false, // 是否显示右上角菜单
          // fileType: 'pdf',
          success: function (res) {
            console.log('打开文档成功')
          }
        })
			},
			DelImg(e) {
				uni.showModal({
					title: '删除附件',
					content: '确定要删除附件吗？',
					cancelText: '取消',
					confirmText: '确定',
					success: res => {
						if (res.confirm) {
							this.imgList.splice(e.currentTarget.dataset.index, 1)
              this.userInfo.path=''
              console.info("🚀 ~ file:userInfo method:success line:498 -----",this.imgList )
						}
					}
				})
			},
			PickerChange(e) {
				this.index = e.detail.value
				this.userInfo.sex = 'boy'
				if(this.index==1){
					this.userInfo.sex = 'girl'
				}
			},
			nationChange(e) {
				let i = e.detail.value
				this.nationIndex = i
				this.userInfo.nation = this.nations[i]
			},
			typeChange(e) {
				let i = e.detail.value
				this.typeIndex = i
				this.userInfo.type = this.typeArr[i]

			},
			eduChange(e) {
				let i = e.detail.value
				this.eduIndex = i
				this.userInfo.education = this.edus[i]

			},
			DateChange(e) {
				// this.date = e.detail.value
				this.userInfo.birthday = e.detail.value
				this.userInfo.age = this.jsGetAge(this.userInfo.birthday)
			},
			yearChange(e) {
        console.info("🚀 ~ file:userInfo method:yearChange line:452 -----",e )
        console.info("🚀 ~ file:userInfo method:yearChange line:453 -----", this.userInfo)
				// this.date = e.detail.value
				this.userInfo.year = e.detail.value
			},
      relaChange(e) {
				// this.date = e.detail.value
				this.userInfo.relation = e.detail.value
			},
			change(data) {
				// this.txt = data.data.join('')
				let arr = []
				if(data[0]!=undefined){
					arr.push( data[0].id)
				}
				if(data[1]!=undefined){
					arr.push( data[1].id)
				}
				if(data[2]!=undefined){
					arr.push( data[2].id)
				}
				this.userInfo.address = arr;
				console.log(data)
				console.log(this.userInfo.address)
			},
			/*根据出生日期算出年龄*/
			jsGetAge(strBirthday){
			    var returnAge;
			    var strBirthdayArr=strBirthday.split("-");
			    var birthYear = strBirthdayArr[0];
			    var birthMonth = strBirthdayArr[1];
			    var birthDay = strBirthdayArr[2];

			    var d = new Date();
			    var nowYear = d.getFullYear();
			    var nowMonth = d.getMonth() + 1;
			    var nowDay = d.getDate();

			    if(nowYear == birthYear){
			        returnAge = 0;//同年 则为0岁
			    }
			    else{
			        var ageDiff = nowYear - birthYear ; //年之差
			        if(ageDiff > 0){
			            if(nowMonth == birthMonth) {
			                var dayDiff = nowDay - birthDay;//日之差
			                if(dayDiff < 0)
			                {
			                    returnAge = ageDiff - 1;
			                }
			                else
			                {
			                    returnAge = ageDiff ;
			                }
			            }
			            else
			            {
			                var monthDiff = nowMonth - birthMonth;//月之差
			                if(monthDiff < 0)
			                {
			                    returnAge = ageDiff - 1;
			                }
			                else
			                {
			                    returnAge = ageDiff ;
			                }
			            }
			        }
			        else
			        {
			            returnAge = -1;//返回-1 表示出生日期输入错误 晚于今天
			        }
			    }
			    return returnAge;//返回周岁年龄
			},
			// ...mapMutations(['logout']),
			//获取列表
			async getUserInfo() {
				let uId = uni.getStorageSync('userId');
				if (uId > "0" && uId != undefined) {

					let t = this;
					t.loaded = false
					let data = await this.$http.get(
						'wx/job_seekers/'+uId,
					);

					console.log(data);
					if(data.birthday==undefined){
						data.birthday='2000'
					}
					t.userInfo = data;
					t.fruitName = data.position_name>''?data.position_name.split(','):[];
					t.fruitId = data.position
					t.imgList = [data.path]
          t.loaded = true
					// if(data.path!=undefined&&data.path>''){
					// 	this.imgList = [{path:data.path}]
					// }


					uni.setStorageSync('userInfo', data);
				}

			},
			navTo(url) {
				this.$api.msg(`跳转到${url}`);
			},
			//退出登录
			toLogout() {
				uni.showModal({
					content: '确定要退出登录么',
					success: (e) => {
						if (e.confirm) {
							this.logout();
							setTimeout(() => {
								uni.navigateBack();
							}, 200)
						}
					}
				});
			},
			//switch
			switchChange(e) {
				let statusTip = e.detail.value ? '打开' : '关闭';
				this.$api.msg(`${statusTip}消息推送`);
			},
			goPage(page) {
			  if(!page){
          uni.showToast({
            title:'敬情期待...',
            icon:'none'
          })
			    return
        }
				uni.navigateTo({
					url: page
				})
			},
		}
	}
</script>

<style lang='scss'>
	page {
		background: $page-color-base;
	}

	.cu-list {
		overflow: hidden;
	}

	.require {
		color: #ff0000;
	}

	.left {
		text-align: right;
	}

	.list-cell {
		display: flex;
		align-items: baseline;
		padding: 4rpx $page-row-spacing;
		line-height: 72rpx;
		position: relative;
		background: #fff;
		height: 40px;
		justify-content: center;

		.user-img {
			height: 35px;
			width: 35px;
			overflow: hidden;
		}

		.cell-more {
			align-self: baseline;
			font-size: $font-lg;
			color: $font-color-light;
			margin-left: 10rpx;
		}

		.cell-tit {
			flex: 1;
			font-size: 36rpx;
			color: $font-color-dark;
			margin-right: 10rpx;
		}

		.promote {
			padding: 5px;
			border: 1px solid #4CA5FE;
			border-radius: 6em;
			margin-left: 10px;
			color: #4CA5FE;
			font-size: 12px !important;
		}

		.cell-tip {
			font-size: 32rpx;
			color: $font-color-light;
		}

		switch {
			transform: translateX(16rpx) scale(.84);
		}
	}

	.cu-btn {
		height: 80rpx;
		width: 100%;
		position: fixed;
		bottom: 5px;
		box-shadow: 0px 3px 6px #4CA5FE;
	}

	.line {
		border-bottom: 1rpx solid #F2F2F2;
	}

	.bottom {
		position: fixed;
		bottom: 0;
		width: 100%;

		.cell-tit {
			color: #FFFFFF !important;
			height: 44px;
		}
	}
</style>
